# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
# Usage (from this directory):
#   sd edit ..\..\..\published\dload\esent.c
#   perl gendload.pl > ..\..\..\published\dload\esent.c
#

my $headerfile = $ARGV[0];
if (!$headerfile)
{
    $headerfile = '.\jethdr.w';
}
open(my $headerfileHandle, "<", $headerfile) or die "Can't open $headerfile!";

my %allApis;
my $lineNumber = 0;
my $readingApi = 0;
my $thisApi;
my $currentApiSignature;

# Build up the list of private/public JET_params.
while ($line = <$headerfileHandle>)
{
    $lineNumber++;

    if ($line =~ /begin_PubEsent/)
    {
        $public = 1;
    }
    elsif ($line =~ /end_PubEsent/)
    {
        $public = 0;
    }

    if ($line =~ /JET_ERR JET_API/)
    {
        $readingApi = 1;
        $currentApiSignature = "";
    }

    while ( $readingApi )
    {
        if ( !$thisApi && ( $line =~ m/(Jet\w+)/ ) )
        {
            $thisApi = $1;
        }

        if ( $readingApi )
        {
            $currentApiSignature .= $line;
        }

        # Look for a right-paren followed by a semicolon. (Ignore SAL.)
        if ( $line =~ m/\)\s*;/ )
        {
            # This signature is done!
            $readingApi = 0;
            last;
        }

        $line = <$headerfileHandle>;
    }

    if ( $thisApi )
    {
        if ( $public )
        {
            $allApis{ $thisApi } = $currentApiSignature;
        }
        $thisApi = "";
    }
}

# Print the header of the file.
print <<__PROLOG__;
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "dspch.h"
#pragma hdrstop

#include <esent.h>

//
// !! WARNING !! The entries below must be in alphabetical order
// and are CASE SENSITIVE (i.e., lower case comes last!)
//
// Put the map before the functions to ensure we have the declarations
// and that our implementations match.
//
// This file is now generated by gendload.pl. Please do not edit this
// file directly.
//
DEFINE_PROCNAME_ENTRIES(esent)
{
__PROLOG__

# Print out the map
foreach $api ( sort( keys %allApis ) )
{
    print "    DLPENTRY($api)\n";
}

print <<__EOCODE1__;
};

DEFINE_PROCNAME_MAP(esent)

__EOCODE1__

# Now print the function stubs.
foreach $api ( sort( keys %allApis ) )
{
    $signature = $allApis{$api};

    # Strip the leading whitespace and the semi-colon.
    $signature =~ s/^s+//;
    $signature =~ s/;//;

    # Convert tabs to spaces.
    $signature =~ s/\t/    /g;

    # Remove the last newline.
    chomp $signature;

    print "static\n$signature\n";
    print <<__EOCODE_BODY__;
{
    return /* no ErrERRCheck - external code */ JET_errInternalError;
}

__EOCODE_BODY__

}

print "\n";
print "// Reminder: Do not manually add new stubs to this file. Instead, use gendload.pl.\n";

